package relu.fbs.jfm;


import java.io.IOException;

import relu.fbs.BadDataException;
import relu.fbs.xt.FBSYearData;
import relu.fbs.xt.FBSFarmData;



/** \internal Takes a series of FBS data files in csv format and convert them to a summary 
 * that could be used for WFM input. The csv files must be named year.csv */
public class FBSToJFM {
	public static void main (String args[]) {
		FBSFarmData nextFarm =null;
		try {
			JFMTimeSeries tser=new JFMTimeSeries();
			for ( int f=0;f<args.length;f++){
				int year = Integer.parseInt(args[f].split("\\.")[0]);
				System.out.println("Reading data for year "+year+" in file "+args[f]);
				int numPassed=0;
				int totalNum=0;
//				FBSYearData yearData=new FBSYearData(args[f],true);
				FBSYearData yearData = FBSYearData.fromCSV(args[f], false);
				nextFarm = yearData.nextFarm();
//				tser.addFarm(nextFarm, year);
				while(nextFarm!=null){
//					System.out.println(nextFarm.farmId);
					JFMFarmData jfdat=JFMFarmData.fromFBSFarmData(nextFarm);
					totalNum++;
//					System.out.println(totalNum);
					if ( jfdat.passAllChecks(nextFarm)){
						numPassed++;
						tser.addFarm(jfdat, year);
						System.out.println(numPassed+" "+totalNum);
//						System.out.println(jfdat);
//						throw new Error("");
					}
					nextFarm=yearData.nextFarm();
				}
				System.out.println("Done .. "+numPassed+" passed of "+totalNum);
				//				tser.addYear(yearData,year);
			}
			int firstYear=Integer.parseInt(args[0].split("\\.")[0]);
			int lastYear=Integer.parseInt(args[args.length-1].split("\\.")[0]);
			tser.exportToDirectory("ts/",5);
			tser.exportToCSV(1);
//			System.out.println("Exporting to average");
//			tser.exportTimeAverageToCSV(firstYear+":"+lastYear+".csv", firstYear, lastYear);			
		}  catch (NumberFormatException ex){
			throw new Error(ex.getMessage());
		} catch (IOException ex){
			throw new Error(ex.getMessage());
		} catch (BadDataException ex){
			throw new Error(nextFarm+ex.getMessage());
		}
	}
}
